//
//  HHEnvironmentObject.swift
//  HHSwiftuiPractice
//
//  Created by YL-Hong on 2023/10/9.

//EnvrionmentObject 和前面说的StateObjecte功能很类似，唯一不同的是。使用 EnvrionmentObject 包装的属性会在全局范围都可以访问使用。只需在父类中注入到环境变量，后续的子类不需要层层传递。

import SwiftUI

class EnvrionmentObjectViewModel: ObservableObject {
    @Published var languages: [String] = []
    
    init() {
        getLanguages()
    }
    
    func getLanguages() {
        languages.append(contentsOf: ["iOS", "Golang", "Java", "C++", ".Net"])
    }
}

struct HHEnvironmentObject: View {
    
    @StateObject var envrionmentViewModel: EnvrionmentObjectViewModel = EnvrionmentObjectViewModel()
      
      var body: some View {
          NavigationView {
              List {
                  
                  ForEach(envrionmentViewModel.languages, id: \.self) { item in
                    
                      NavigationLink {
                            DetailsView(title: item)
                        } label: {
                            Text(item)
                                .frame(maxWidth: .infinity)
                                .background(
                                  Color.yellow
                                )
                        }
                      
                  }
              }
              .navigationTitle("Envrionment Object")
          }
          .tint(Color.black)
          .environmentObject(envrionmentViewModel)
      }

}

struct DetailsView: View {
//    @ObservedObject var envrionmentViewModel: EnvrionmentObjectViewModel
    var title: String
    
    var body: some View {
        ZStack {
            Color.mint.edgesIgnoringSafeArea(.all)
            
            NavigationLink {
                OtherView()
            } label: {
                Text(title)
                    .font(.headline)
                    .fontWeight(.semibold)
                    .foregroundColor(Color.mint)
                    .padding()
                    .padding(.horizontal)
                    .background(Color.white.cornerRadius(25.0))
            }
        }
    }
}

struct OtherView: View {
//    @ObservedObject var envrionmentViewModel: EnvrionmentObjectViewModel
    @EnvironmentObject var envrionmentViewModel: EnvrionmentObjectViewModel
    
    var body: some View {
        ZStack {
            LinearGradient(
                colors: [Color.gray, Color.blue],
                startPoint: .topLeading,
                endPoint: .bottomTrailing)
            .edgesIgnoringSafeArea(.all)
            
            VStack {
                ForEach(envrionmentViewModel.languages, id: \.self) { item in
                    Text(item)
                        .font(.title2)
                        .foregroundColor(Color.white)
                }
            }
        }
    }
}


struct HHEnvironmentObject_Previews: PreviewProvider {
    static var previews: some View {
        HHEnvironmentObject()
    }
}
